<template>
    <!--    用户搜索条件框-->
    <div class="cardContent">
        <a-form
                ref="formRef"
                layout="inline"
                name="advanced_search"
                class="ant-advanced-search-form"
                :model="searchData">
            <a-form-item label="菜单名称">
                <a-input v-model:value="searchData.keyword" placeholder="请输入菜单名称"></a-input>
            </a-form-item>
            <a-form-item>
                <a-space>
                    <a-button type="primary" @click="load()">搜索</a-button>
                    <a-button type="default" @click="reset">重置</a-button>
                </a-space>
            </a-form-item>
        </a-form>
    </div>
    <!--    用户列表展示-->
    <div class="cardContent">
        <a-button type="primary" @click="openModal({menuType:0,isPublic:0})">新增</a-button>
        <a-table :dataSource="permissionTree"
                 style="margin-top: 10px"
                 class="ant-table-striped"
                 :columns="columns"
                 :pagination="false"
                 :indent-size="25"
                 :row-key="record => record.id"
                 :row-class-name="(_record, index) => (index % 2 === 1 ? 'table-striped' : null)"
                 size="small"
                 bordered>
            <template #bodyCell="{text,record,index,column}">
                <template v-if="column.key == 'isPublic'">
                    {{text == 0 ? "否" : "是"}}
                </template>
                <template v-if="column.key == 'menuType'">
                    {{text == 0 ? "一级菜单" : (text == 1 ? "子菜单" : "按钮权限")}}
                </template>
                <template v-if="column.key == 'icon'">
                    <component :is="$antIcons[text]"/>
                </template>
                <a-space v-if="column.key == 'action'">
                    <a-button type="primary" @click="openModal(record)">编辑</a-button>
                    <a-popconfirm
                            title="是否确认删除?"
                            ok-text="是"
                            cancel-text="否"
                            @confirm="okDelete(record.id)"
                    >
                        <a-button type="danger">删除</a-button>
                    </a-popconfirm>
                </a-space>
            </template>
        </a-table>
    </div>
    <a-drawer
            v-model:visible="visible"
            class="custom-class"
            width="600"
            title="新增或编辑"
            placement="right"
            :footer-style="{textAlign: 'right'}"
    >
        <a-form
                :model="permission"
                :label-col="{ span: 4 }"
                :wrapper-col="{ span: 20 }"
                autocomplete="off">
            <a-form-item label="菜单类型">
                <a-radio-group v-model:value="permission.menuType" button-style="solid">
                    <a-radio-button @click="permission.parentId = 0" :value="0">一级菜单</a-radio-button>
                    <a-radio-button @click="permission.parentId = null" :value="1">子菜单</a-radio-button>
                    <a-radio-button @click="permission.parentId = null" :value="2">按钮权限</a-radio-button>
                </a-radio-group>
            </a-form-item>
            <a-form-item label="菜单名称" v-bind="permissionRef.validateInfos.name">
                <a-input v-model:value="permission.name"/>
            </a-form-item>
            <a-form-item v-if="permission.menuType !== 0"
                         v-bind="permissionRef.validateInfos.parentId"
                         label="上级菜单">
                <a-select
                        ref="select"
                        v-model:value="permission.parentId"
                        :field-names="{label: 'name',value: 'id'}"
                        :options="permission.menuType == 1 ? childrenMenuParents : buttonPermissionParents"
                />
            </a-form-item>
            <a-form-item v-if="permission.menuType == 1"
                         v-bind="permissionRef.validateInfos.url"
                         label="访问路径">
                <a-select
                        ref="select"
                        v-model:value="permission.url"
                        :field-names="{label: 'path',value: 'path'}"
                        :options="routerList"
                />
            </a-form-item>
            <a-form-item v-if="permission.menuType != 2"
                         v-bind="permissionRef.validateInfos.icon"
                         label="菜单图标">
                <iconPicker v-model:icon="permission.icon">
                    <template #iconSelect>
                        <a-input v-model:value="permission.icon"/>
                    </template>
                </iconPicker>
            </a-form-item>
            <a-form-item v-if="permission.menuType != 0"
                         v-bind="permissionRef.validateInfos.perms"
                         label="权限编码">
                <a-input v-model:value="permission.perms"/>
            </a-form-item>
            <a-form-item label="排序" v-bind="permissionRef.validateInfos.sortNo">
                <a-input-number v-model:value="permission.sortNo"/>
            </a-form-item>
            <a-form-item label="是否公共资源">
                <a-switch v-model:checked="permission.isPublic"
                          :checked-value="1"
                          :un-checked-value="0"
                          checked-children="开"
                          un-checked-children="关"/>
            </a-form-item>
        </a-form>
        <template #footer>
            <a-space>
                <a-button type="default" @click="visible = false">取消</a-button>
                <a-button type="primary" @click="saveOrUpdate">保存</a-button>
            </a-space>
        </template>
    </a-drawer>
</template>

<script>
    import {ref, onMounted, watch} from 'vue'
    import axios from 'axios'
    import {Form, message} from 'ant-design-vue';
    import {DownOutlined, UpOutlined} from '@ant-design/icons-vue';
    import {arrayToTree, isEmpty} from "@/utils/Tool";
    import iconPicker from "@/components/iconPicker";
    import {useRouter} from 'vue-router'

    export default {
        name: "Permission",
        components: {
            DownOutlined,
            UpOutlined,
            iconPicker
        },
        setup() {
            const columns = [
                {
                    title: '菜单名称',
                    dataIndex: 'name',
                    key: 'name',
                    align: 'left',
                    width: 200
                },
                {
                    title: '类型',
                    dataIndex: 'menuType',
                    key: 'menuType',
                    align: 'center',
                    width: 150
                },
                {
                    title: '图标',
                    dataIndex: 'icon',
                    key: 'icon',
                    align: 'center',
                    width: 50
                },
                {
                    title: '路径',
                    dataIndex: 'url',
                    key: 'url',
                    width: 150
                },
                {
                    title: '公共资源',
                    dataIndex: 'isPublic',
                    key: 'isPublic',
                    align: 'center',
                    width: 100
                },
                {
                    title: '操作',
                    key: 'action',
                    align: 'center',
                    width: 200
                }
            ]
            const permission = ref({
                name: '',
                parentId: undefined,
                url: '',
                icon: '',
                perms: '',
                sortNo: undefined
            })
            const permissionList = ref()
            const permissionTree = ref()
            const childrenMenuParents = ref([])
            const buttonPermissionParents = ref([])
            const searchData = ref({})
            const router = useRouter()
            const routerList = ref([])
            const visible = ref(false);

            const useForm = Form.useForm
            const permissionRef = useForm(permission, ref({}))

            watch(() => permission.value.menuType, () => {
                console.log("查看当前", permission.value)
                if (permission.value.menuType == 0) {
                    permission.value.url = ''
                    permission.value.perms = ''
                    permissionRef.rulesRef.value = {
                        name: [{required: true, message: '请输入权限菜单名称', trigger: ['change']}],
                        icon: [{required: true, message: '请选择图标', trigger: ['change']}],
                        sortNo: [{required: true, message: '请输入序号', trigger: ['change']}],
                    }
                } else if (permission.value.menuType == 1) {
                    permissionRef.rulesRef.value = {
                        name: [{required: true, message: '请输入权限菜单名称', trigger: ['change']}],
                        icon: [{required: true, message: '请选择图标', trigger: ['change']}],
                        sortNo: [{required: true, message: '请输入序号', trigger: ['change']}],
                        parentId: [{required: true, message: '请选择上级菜单', trigger: ['change']}],
                        url: [{required: true, message: '请选择访问路径', trigger: ['change']}],
                        perms: [{required: true, message: '请输入权限编码', trigger: ['change']}],
                    }
                } else {
                    permission.value.url = ''
                    permissionRef.rulesRef.value = {
                        name: [{required: true, message: '请输入权限菜单名称', trigger: ['change']}],
                        sortNo: [{required: true, message: '请输入序号', trigger: ['change']}],
                        parentId: [{required: true, message: '请选择上级菜单', trigger: ['change']}],
                        perms: [{required: true, message: '请输入权限编码', trigger: ['change']}],
                    }
                }
            })

            const saveOrUpdate = () => {
                permissionRef.validate().then(() => {
                    console.log("通过校验")
                    axios.post('/permission/saveOrUpdate', permission.value).then(rs => {
                        console.log("新增或修改结果：", rs)
                        if (rs.code == 200) {
                            visible.value = false
                            message.success("操作成功")
                            if (!isEmpty(permission.value.id)) {
                                location.reload()
                            }else {
                                load()
                            }
                        } else {
                            message.error(rs.message)
                        }
                    })
                }).catch(() => {
                    console.log("校验失败")
                })

            }

            const okDelete = (id) => {
                console.log("要删除的ID：" + id)
                axios.delete('/permission/deleteById/' + id).then(rs => {
                    if (rs.code == 200) {
                        message.success("删除成功")
                        load()
                    } else {
                        message.error(rs.message)
                    }
                })
            }

            const openModal = (obj) => {
                console.log("模态框参数：", obj)
                permission.value = JSON.parse(JSON.stringify(obj))
                if (isEmpty(permission.value.id)) {
                    console.log("空的")
                    permissionRef.resetFields()
                    console.log("参数：", permission.value)
                }
                axios.get('permission/queryAll').then(rs => {
                    childrenMenuParents.value = []
                    buttonPermissionParents.value = []
                    permissionList.value = rs.data
                    permissionList.value.forEach((val) => {
                        if (val.menuType == 0) {
                            childrenMenuParents.value.push(val)
                        }
                        if (val.menuType == 1) {
                            buttonPermissionParents.value.push(val)
                        }
                    })
                    buttonPermissionParents.value.unshift({id: 0, name: '无上级菜单'})
                })
                if (permission.value.parentId == null) {
                    permission.value.parentId = 0
                }
                visible.value = true;
            }

            axios.get('permission/queryAll').then(rs => {
                permissionList.value = rs.data
            })

            const load = () => {
                axios.get('/permission/queryByPermissionName', {
                    params: {
                        keyword: searchData.value.keyword,
                    }
                }).then(rs => {
                    console.log("查找结果：", rs)
                    permissionTree.value = arrayToTree(rs.data, 0)
                })
            }

            const reset = () => {
                searchData.value = {}
                load()
            }

            onMounted(() => {
                router.options.routes.forEach(val => {
                    if (val.name == 'home') {
                        val.children.forEach(value => {
                            routerList.value.push(value)
                        })
                    }
                })
                console.log("路由列表", routerList.value)
                load()
            })
            return {
                columns,
                permission,
                permissionList,
                load,
                searchData,
                reset,
                visible,
                openModal,
                saveOrUpdate,
                okDelete,
                permissionTree,
                childrenMenuParents,
                buttonPermissionParents,
                routerList,
                permissionRef
            }
        }
    }
</script>

<style scoped>
    .cardContent {
        background: #fff;
        margin: 10px 10px 0 10px;
        padding: 15px;
    }

    .ant-advanced-search-form {
        background: rgba(255, 255, 255, 0.04);
        /*padding: 15px;*/
        border-radius: 2px;
    }

    .ant-table-striped :deep(.table-striped) td {
        background-color: #fafafa;
    }
</style>